//
//  MNDOpenDepositoryTenderViewController.m
//  minidai
//
//  Created by 容贤郁 on 2018/3/14.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDWebViewController.h"
#import <TTTAttributedLabel.h>
#import "UIButton+JKCountDown.h"
#import "MNDDepositWebViewController.h"
#import "MNDUserAutoTenderRank.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDAlertViewController.h"
#import "UIImage+JKColor.h"

typedef NS_ENUM(NSInteger,TextFieldType) {
    TextFieldTypeLeastYearApr = 101,
    TextFieldTypeMostYearApr,
    TextFieldTypeLeastMonth,
    TextFieldTypeMostMonth
    
};

@interface MNDOpenDepositoryTenderViewController () <TTTAttributedLabelDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *captchaTextField;
@property (weak, nonatomic) IBOutlet UIButton *sendCaptchaButton;
@property (weak, nonatomic) IBOutlet UISwitch *tenderSwitch;

@property (weak, nonatomic) IBOutlet UITextField *minYearAprTextField;
@property (weak, nonatomic) IBOutlet UITextField *maxYearAprTextField;
@property (weak, nonatomic) IBOutlet UITextField *minMonthTextField;
@property (weak, nonatomic) IBOutlet UITextField *maxMonthTextField;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *noticeLabel;
@property (weak, nonatomic) IBOutlet UIView *rateView;
@property (weak, nonatomic) IBOutlet UIView *monthView;

@property (nonatomic, strong) MNDUserAutoTenderRank *rankModel;

@property (weak, nonatomic) IBOutlet UILabel *noteLabel;

@property (nonatomic, copy) NSString *alertMessage;

@property (weak, nonatomic) IBOutlet UIView *paramView;

@end

@implementation MNDOpenDepositoryTenderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self.paramView setHidden:self.isResign];
    //4.5.3版本之后此页面不需要设置投标参数
    [self.paramView setHidden:YES];
    
    self.captchaTextField.placeholder = [NSString stringWithFormat:@"请输入尾号%@收到的验证码", [self.phoneNumber substringFromIndex:self.phoneNumber.length - 4]];
    
    [self.sendCaptchaButton addTarget:self action:@selector(sendCaptchaAction:) forControlEvents:UIControlEventTouchUpInside];

    [self sendCaptchaAction:self.sendCaptchaButton];
    
    __block UITextField *captchaField = self.captchaTextField;
    
    [self.captchaTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 6) {
            captchaField.text = [x substringToIndex:6];
        }
    }];
    
    __block UITextField *minMonth = self.minMonthTextField;
    [self.minMonthTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        
        if (x.integerValue < 1) {
            minMonth.text = @"1";
        }
        
        if (x.integerValue > 12) {
            minMonth.text = @"12";
        }
        
        if (x.length <= 0) {
            minMonth.text = @"";
        }
    }];
    
    __block UITextField *maxMonnth = self.maxMonthTextField;
    [self.maxMonthTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        
        if (x.integerValue < 1) {
            maxMonnth.text = @"1";
        }
        
        if (x.integerValue > 12) {
            maxMonnth.text = @"12";
        }
        if (x.length <= 0) {
            maxMonnth.text = @"";
        }
    }];
    
    __block UITextField *minApr = self.minYearAprTextField;
    [self.minYearAprTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        
        if (x.doubleValue <= 0) {
            minApr.text = @"1";
        }
        
        if (x.doubleValue > 100) {
            minApr.text = @"30";
        }
        
        if (x.length <= 0) {
            minApr.text = @"";
        }
    }];
    
    __block UITextField *maxApr = self.maxYearAprTextField;
    [self.maxYearAprTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        
        if (x.doubleValue <= 0) {
            maxApr.text = @"1";
        }
        
        if (x.doubleValue > 100) {
            maxApr.text = @"30";
        }
        
        if (x.length <= 0) {
            maxApr.text = @"";
        }
    }];
    
    [self loadSignIntroductionMessage];
    
    [self addAgreementLabelAttribute];
    
    [self initialBackButton];
    
    [self loadUserAutoTenderRanking];
    
    [self loadDepositInfo];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    [self.navigationController.navigationBar setShadowImage:image];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initialRightBarButton {
    UIImage *itemImage = [UIImage imageNamed:@"notice_help_icon"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: [itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
    //    [item setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)rightBarButtonAction:(id)sender {
    if (self.alertMessage) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        MNDAlertViewController *alertController = [storyboard instantiateViewControllerWithIdentifier:[MNDAlertViewController description]];
        [KeyWindow addSubview:alertController.view];
        [self.tabBarController addChildViewController:alertController];
        
        alertController.alertTitle = @"自动投标授权说明";
        alertController.alertMessage = self.alertMessage;
    }
}

- (void)loadSignIntroductionMessage {
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_SIGN_INTRODUCTION parameters:[MNDSign signedParamWithDict:@{@"type": @"auto_tender"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.alertMessage = responseModel.data[@"introductions"];
            [weakself initialRightBarButton];
        }
    } onFailure:^(NSError *error) {
        
    }];
}

- (void)loadDepositInfo {
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                [NetworkProgressHUD hideHud];
                
                weakself.noteLabel.text = responseModel.msg[@"error"];
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } else {
            [self backAction:nil];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadUserAutoTenderRanking {
    NSDictionary *param = [MNDSign signedParam];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_FORECAST_TENDER_RANKING parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            
            weakself.rankModel = [MNDUserAutoTenderRank mj_objectWithKeyValues:responseModel.data];
            [weakself configAutotenderRank];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)grantAutoTender {
    
//    NSString *tenderStatus = self.tenderSwitch.isOn ? @"1" : @"-1";
//    NSDictionary *dict = @{@"smscode": self.captchaTextField.text,
//                           @"channel": @"app",
//                           @"auto_tender_status": tenderStatus,
//                           @"borrow_least_year_apr": self.minYearAprTextField.text,
//                           @"borrow_most_year_apr": self.maxYearAprTextField.text,
//                           @"borrow_least_deadline": self.minMonthTextField.text,
//                           @"borrow_most_deadline": self.maxMonthTextField.text
//                           };
//    NSLog(@"params: %@", dict);
    NSDictionary *dict = @{@"smscode": self.captchaTextField.text,
                           @"channel": @"app"
                           };
    NSDictionary *param = [MNDSign signedParamWithDict:dict];
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_AUTO_TENDER_AUTHORIZATION parameters:param method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"自动投标授权";
            webVC.fromNaviIndex = weakself.fromNaviIndex;

            [weakself.navigationController pushViewController:webVC animated:YES];
            
        } else {
            [weakself loadDepositInfoWithErrorStr:responseModel.msg[@"error"]];
        }
        
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadDepositInfoWithErrorStr:(NSString *)errorStr {
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                NSString *signStr = responseModel.msg[@"sign"];
                //未完成当前步骤弹出报错信息
                if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
                    [NetworkProgressHUD showHudMsg:errorStr];
                    //已完成当前步骤直接跳到下一步
                } else if ([signStr isEqualToString:kSignAutoTransfer]) {
                    [NetworkProgressHUD hideHud];
                    
                    MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
                    transferVC.fromNaviIndex = weakself.fromNaviIndex;
                    transferVC.phoneNumber = weakself.phoneNumber;
                    
                    [weakself.navigationController pushViewController:transferVC animated:YES];
                } else {
                    [NetworkProgressHUD showHudMsg:@"您已开通存管"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakself backAction:nil];
                    });
                }
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } else {
            [NetworkProgressHUD showHudMsg:@"您已开通存管"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself backAction:nil];
            });
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configAutotenderRank {
    self.minYearAprTextField.text = self.rankModel.borrowLeastYearApr;
    self.maxYearAprTextField.text = self.rankModel.borrowMostYearApr;
    self.minMonthTextField.text = self.rankModel.borrowLeastDeadline;
    self.maxMonthTextField.text = self.rankModel.borrowMostDeadline;
}

- (void)sendCaptchaAction:(UIButton *)sender {
    NSDictionary *dict = @{@"user_phone": self.phoneNumber, @"channel": @"app", @"srvtxcode": @"autoBidAuthPlus"};
    
    NSDictionary *param = [MNDSign signedParamWithDict:dict];
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SEND_CAPTCHA parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            [weakself.sendCaptchaButton jk_startTime:30 title:@"重新发送" waitTittle:@"秒后重发"];
            
        } else {
            NSDictionary *dict = responseModel.msg;
            
            [NetworkProgressHUD showHudMsg:dict[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (IBAction)switchAction:(UISwitch *)sender {
    [self.rateView setHidden:!sender.isOn];
    [self.monthView setHidden:!sender.isOn];
}

- (IBAction)grantAction:(UIButton *)sender {
    if (self.captchaTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入手机验证码"];
        return;
    }
    
    if (self.minYearAprTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入最小年利率范围"];
        return;
    }
    
    if (self.maxYearAprTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入最大年利率范围"];
        return;
    }
    
    if (self.minMonthTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入最小期限范围"];
        return;
    }
    
    if (self.maxMonthTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入最大期限范围"];
        return;
    }
    
    if (self.minYearAprTextField.text.doubleValue > self.maxYearAprTextField.text.doubleValue) {
        [NetworkProgressHUD showHudMsg:@"最小年利率范围不能大于最大年利率范围"];
        return;
    }
    
    if (self.minMonthTextField.text.integerValue > self.maxMonthTextField.text.integerValue) {
        [NetworkProgressHUD showHudMsg:@"最小期限范围不能大于最大期限范围"];
        return;
    }
    
    [self grantAutoTender];
}

- (void)addAgreementLabelAttribute {
    //设置高亮颜色
    self.noticeLabel.highlightedTextColor = kColorDarkOrange;
    //检测类型
    self.noticeLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.noticeLabel.delegate = self;
    //不显示下划线
    self.noticeLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text = @"点击按钮表示您同意《自动投标授权协议》";
    [self.noticeLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange = [[mutableAttributedString string] rangeOfString:@"《自动投标授权协议》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorDarkOrange} range:linkRange];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange = [text rangeOfString:@"《自动投标授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url = [NSURL URLWithString:kAutoTenderAccord];
    [self.noticeLabel addLinkToURL:url withRange:linkRange];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    
    webVC.title = @"自动投标授权协议";
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.fromNaviIndex];
    [self.navigationController popToViewController:viewController animated:YES];
}


#pragma mark -UITextFieldDelegate
//设置textfield输入内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField.tag == TextFieldTypeLeastYearApr || textField.tag == TextFieldTypeMostYearApr) {
        NSScanner      *scanner    = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange         pointRange = [textField.text rangeOfString:@"."];
        if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        
        if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
        {
            return NO;
        }
        
        short remain = 2; //默认保留2位小数
        
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
        
    }
    
    return YES;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
